<script setup>
/**
 * @description: 抽屉组件-文字标题
 * @param {*}
 * @return {*}
 */
import {
  ref,
  reactive,
  nextTick,
  watch,
  onMounted,
  computed,
  createVNode,
  defineEmits,
} from "vue";
import dayjs from "dayjs";
import utils from "@/common/utils/utils.js";

// 处理配置应用到全部字幕组
import {
  applyallGlobalTitle,
  // 视频截取首帧画面
  captureFirstFrame,
} from "@/common/utils/richTextProcessing.js";

// 获取随机id
import { nanoid } from "nanoid";

// 花字组件
import FancyFont from "./FancyFont.vue";
const fancyFont = ref(null);

// 素材库组件
import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";

import newChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/newChooseMaterial.vue";

// icon
import {
  CloseOutlined,
  CopyOutlined,
  ExclamationCircleOutlined,
  PlusOutlined,
  InfoCircleOutlined,
} from "@ant-design/icons-vue";
// 轻提示
import { message, Modal } from "ant-design-vue";
// 自定义工具
import {
  changeFocus,
  baseText_config,
  hexToRgba,
  calculateDraggableArea,
  measureTextWithSpan,
  resetXY,
  clearWrap,
} from "../../utools/index.js";
//
import request from "@/common/utils/request";

import AIWritingAssistant from "@/views/shotstack/MuseMixedCut/mixedCutCreat/components/AIWritingAssistant.vue";

// 仓库
// import store from "@/store";

// 手机组件
import { DraggableContainer } from "vue3-draggable-resizable";

// 风险词检测组件
import Risk_test from "./Component/Risk_test.vue";
const Risk_testRefs = ref([]);

import Vue3DraggableResizable from "vue3-draggable-resizable";
//default styles
import "vue3-draggable-resizable/dist/Vue3DraggableResizable.css";
// 仓库
import { useStore } from "vuex";
import RiskWordDetection from "../components/riskWordDetecDrawer.vue";
// 文案库组件
import CopyLibraryModal from "@/components/AddTextModal/CopyLibraryModal.vue";

// 处理文案导入
import { textImportToTitle } from "@/common/utils/richTextProcessing.js";

const store = useStore();
let state = ref([]);

// 素材库开关
const materiallibraryShow = ref(false);

const closeChooseMaterial = (data) => {
  textImportToTitle({
    data,
    state,
    activeTextarea,
    copyLibraryModal,
    type: "Global",
    currentDrawerIndex: null,
  });
  return
  // debugger
  if (data == "") {
    copyLibraryModal.value && copyLibraryModal.value.closeModal();
    return;
  }
  const findTarget = state.value.find((ele) => ele.id == activeTextarea.value);
  findTarget.text_material_id = data.id;

  if (!!findTarget) {
    findTarget.text = data.slice(0, 500);
    nextTick(() => {
      const textareaDom = document.querySelector(
        `[data-textareaId="${activeTextarea.value}"]`
      );
      textareaDom.style.height = "auto";
      textareaDom.style.height = `${textareaDom.scrollHeight}px`;
    });
    copyLibraryModal.value && copyLibraryModal.value.closeModal();
  }
};

// 仓库中的混剪数据
const VideoMashup = computed(() => {
  return store.state.shotstack.VideoMashup;
});


// 背景设置的参数
const bgc = computed(() => {
  const data = store.state.shotstack.VideoMashup.background
  // debugger
  if (data?.type == 1) {
    return {
      'background': data.rgba
    }
  } else if (data?.type == 2 || data?.type == 3) {
    let url = data.material_urls[0]
    return {
      'background': `url(${url})`,
      'background-position': 'center',
      'background-size': 'cover'
    }
  } else {
    return {
      'background': '#707070'
    }
  }
});

// 从仓库中拿到全局文字标题数据
const global_text_config = computed(() => {
  console.log();
  return store.state.shotstack.VideoMashup.global_text_config;
});

const props = defineProps({
  title: {
    type: String,
    default: "添加文字",
  },
});

// 当前预览的下标
const currentDrawerIndex = ref(0);

// 获取风险词文字数组
// const text_arr = computed(() => {
//   if (TitleArr.value[isActive.value]?.data) {
//     console.log(TitleArr.value[isActive.value]?.data, 'TitleArr.value[isActive.value]?.data');
//     const arr = TitleArr.value[isActive.value].data.map(ele => ele.text)
//     return {
//       arr,
//       text: arr.join('')
//     }
//   } else {
//     return {
//       arr: [''],
//       text: ''
//     }
//   }
// })

// 文本框自动适应高度
const autoResize = (event) => {
  const textarea = event.target;
  // 重置textarea的高度（这步很重要，能够在删除内容时减小textarea的高度）
  textarea.style.height = "auto";
  // 让textarea的高度等于它的滚动高度，这样就能够完全容纳它的内容
  textarea.style.height = `${textarea.scrollHeight}px`;
  console.log(
    textarea.scrollHeight,
    "textarea.scrollHeighttextarea.scrollHeighttextarea.scrollHeight"
  );
};

// 高亮的项
const activeTextarea = ref(0);

// 初始修改高亮标题的高度
const changeHeight = () => {
  nextTick(() => {
    changeFocus(`[data-textareaId="${activeTextarea.value}"]`, false);
    const textareaDom = document.querySelector(
      `[data-textareaId="${activeTextarea.value}"]`
    );
    const findTarget = state.value.find(
      (ele) => ele.id == activeTextarea.value
    );
    textareaDom && (textareaDom.style.height = "auto");
    nextTick(() => {
      // debugger
      console.log(textareaDom.scrollHeight, "高度高度");
      if (!!findTarget && findTarget.text == "") {
        textareaDom && (textareaDom.style.height = `${26}px`);
      } else {
        textareaDom &&
          (textareaDom.style.height = `${textareaDom.scrollHeight}px`);
      }
    });
    //改变当前侦听的聚焦项
    unobserveAllSpans();
    observeActiveSpan();
  });
};

// 实时变更聚焦点
watch(
  () => activeTextarea.value,
  () => {
    changeHeight();
  }
);

// 实时获取高亮的项的index
const activeIndex = computed(() => {
  const tergetArr = state.value;
  return tergetArr.findIndex((ele) => ele.id === activeTextarea.value);
});

const textAreaChange = (index) => {
  // 编辑的这一组
  const tergetArr = state.value;
  // 编辑的这一项
  const targetItem = tergetArr[index];

  setTimeout(() => {
    // 修改x的值
    const dom = document.getElementById("cover_" + targetItem.id);
    const width = dom?.offsetWidth;
    console.log(width, "span 的宽度");
    targetItem.x = targetItem.showX - width / 2;
    // debugger
    console.log(targetItem.x, " 修改后的xxxxxxxxxxxxxxxx");
  }, 0);
};

// 删除条件为, 不能删除第一个项
const textareaKeydown = (event, index) => {
  // 编辑的这一组
  const tergetArr = state.value;
  // 编辑的这一项
  const targetItem = tergetArr[index];

  if (event.key == "Backspace" && targetItem) {
    if (tergetArr.length <= 1 && targetItem.text.length <= 0) {
      event.preventDefault();
      message.warning("至少需要一个标题!");
      return;
    } else if (tergetArr[index].text.length <= 0) {
      event.preventDefault();
      if (index < tergetArr.length - 1) {
        activeTextarea.value = tergetArr[index + 1].id;
      } else {
        activeTextarea.value = tergetArr[index - 1].id;
      }
      tergetArr.splice(index, 1);
    }
  } else if (event.shiftKey && event.key == "Enter") {
    return;
  } else if (event.key == "Enter") {
    event.preventDefault();
    addTextareaItem(index, "add");
  }
};

// 点击项获取焦点
const focusItem = (id) => {
  activeTextarea.value = id;
};

// 字体组件的更新和修改
const updateState = (data) => {
  // 确保目标对象存在，否则使用一个空对象作为默认值
  const target = state.value?.[activeIndex.value] || {};
  Object.assign(target, { ...data });
};

// 添加标题
const addTextareaItem = (index, type) => {
  const tergetArr = state.value;
  if (tergetArr.length >= 5) {
    message.warning("最多只能添加5个标题!");
    return;
  }
  const timeId = nanoid();
  if (type === "add") {
    const baseText_config_data = baseText_config();
    baseText_config_data.id = timeId;
    tergetArr.splice(index + 1, 0, baseText_config_data);
  } else if (type === "copy") {
    tergetArr.splice(index + 1, 0, {
      ...tergetArr[index],
      id: timeId,
    });
  }
  activeTextarea.value = timeId;
};

let copyLibraryModal = ref(null); //文案库导入组件实例
const openCopyLibraryModal = () => {
  copyLibraryModal.value && copyLibraryModal.value.showModal();
};

// 控制抽屉的显示与隐藏
const visible = ref(false);

const resizeObserver = ref(null);

const openDrawer = (index) => {

  // 侦听span的宽度变化
  resizeObserver.value = new ResizeObserver((entries) => {
    for (let entry of entries) {
      // console.log(entry, '元素变化', activeTextarea.value);
      // console.log(entry, '元素变化', activeTextarea.value);
      const computedStyle = getComputedStyle(entry.target);
      // 计算包含 padding 的宽度
      const paddingLeft = parseFloat(computedStyle.paddingLeft);
      const paddingRight = parseFloat(computedStyle.paddingRight);
      const totalWidth = entry.contentRect.width + paddingLeft + paddingRight;
      spanWidth.value = totalWidth;
      const target = state.value.find((ele) => ele.id == activeTextarea.value);
      // state.value[currentDrawerIndex.value].text_config[activeIndex.value];
      console.log(spanWidth.value, "span 的宽度");
      if (spanWidth.value && target) {
        target.x = target.showX - spanWidth.value / 2;
      }
      console.log(target.x, " 修改后的xxxxxxxxxxxxxxxx", activeTextarea.value);
    }
  });

  useBgc();

  // 修改初始赋值
  TitleArr.value = global_text_config.value.configs.map((ele, index) => {
    return {
      label: "标题组",
      id: index + 1,
      isselected: false,
      data: JSON.parse(JSON.stringify(ele)),
    };
  });
  isActive.value = 0;
  if (global_text_config.value.configs[0][0].text.length == 0) {
    // 这是 初始化 的逻辑  应该用判断取走
    currentDrawerIndex.value = 0;
    // 克隆数据, 用于修改 最后保存
    state.value = JSON.parse(
      JSON.stringify(global_text_config.value.configs[0])
    );
    // 如果没有ID  添加id属性
    state.value.forEach((ele) => {
      !ele?.id && (ele.id = nanoid());
    });
    // 初始赋值id
    activeTextarea.value = state.value[0].id;
    // activeTextarea.value 为 1 是上面 lodash生成的 id 走到这里 没问题
    visible.value = true;

    getFontClass();
    setTimeout(() => {
      phoneVisible.value = true;
    }, 550);
  } else {
    // 有值要做数据回显
    state.value = JSON.parse(
      JSON.stringify(global_text_config.value.configs[0])
    );
    activeTextarea.value = state.value[0].id;
    // activeTextarea.value 为 1 是上面 lodash生成的 id 走到这里 没问题
    visible.value = true;
    getFontClass();
    setTimeout(() => {
      phoneVisible.value = true;
    }, 550);
  }

  // 初始修改高亮标题的高度
  changeHeight();

  console.log(
    state.value,
    "state.valuestate.valuestate.valuestate.valuestate.value"
  );
};
const background = ref({ url: "transparent", type: "color" });

// 使用的背景
const useBgc = async () => {
  // 判断使用的背景
  const find = VideoMashup.value.resource_data.find(
    (ele) => ele.material_list.length
  );

  if (!find) return (background.value = { url: "transparent", type: "color" });
  const material = find.material_list[0];

  if (material?.scene_type == "video") {
    const url = await captureFirstFrame(material.material_url);
    
    if (url) {
      background.value = { url, type: "img" };
    } else {
      background.value = "transparent";
      background.value = { url: "transparent", type: "color" };
    }
  } else if (material?.scene_type == "image") {
    const url = material.material_url;
    url
      ? (background.value = { url, type: "img" })
      : (background.value = { url: "transparent", type: "color" });
  } else {
    background.value = { url: "transparent", type: "color" };
  }
};

// 开始侦听所有的span 元素
const observeActiveSpan = () => {
  // debugger
  nextTick(() => {
    const activeElement = document.getElementById(
      "cover_" + activeTextarea.value
    );
    if (activeElement) {
      resizeObserver.value.observe(activeElement);
    } else {
      console.warn("找不到元素", "cover_" + activeTextarea.value);
    }
  });
};

// 定义要发出的自定义事件及其参数类型
const emits = defineEmits(["GlobTitleState"]);
const globalLabel = ref("");
const closeDrawer = () => {
  if (
    store.state.shotstack.VideoMashup.global_text_config &&
    store.state.shotstack.VideoMashup.global_text_config.configs[0].length > 0
  ) {
    globalLabel.value =
      store.state.shotstack.VideoMashup.global_text_config.configs[0][0].text;
  }
  emits("GlobTitleState", globalLabel.value);
  visible.value = false;
  phoneVisible.value = false;
};

/**
 * 手机相关
 */

const radioType = computed(() => store.getters.clipJSON?.aspect_ratio);

// 控制手机显示隐藏
const phoneVisible = ref(false);
// 加载效果
const loading = ref(false);

const coverList = ref([]);

// 获取渲染的每一项数据
const getPosition = computed(() => {
  const targetData = JSON.parse(
    JSON.stringify(state.value[currentDrawerIndex.value])
  );
  targetData.forEach((ele) => {
    const dom = document.getElementById("cover_" + ele.id);
    nextTick(() => {
      (ele.width = dom?.offsetWidth || 0),
        (ele.height = dom?.offsetHeight || 0),
        (ele.active = false);
    });
  });
  return targetData;
});

// 获取当前选中的弹幕
const resizableStyle = computed(() => {
  const sizeData = calculateDraggableArea(
    +VideoMashup.value.width,
    +VideoMashup.value.height
  );

  let returnVal =
    background.value.type == "color"
      ? {
        background: background.value.url,
      }
      : {
        background: `url(${background.value.url})`,
        "background-size": "100%" /* 或者其他合适的设置 */,
        "background-repeat": "no-repeat",
        "background-position": "center",
      };

  return {
    // backgroundImage: `url(https://ui.biaodianyun.com/dy-saas/admin-pc/assets/bg_cover-d353011d.png), url(${coverForm.value.poster_url}), url(https://hf.pigcms.com/static/wxapp/images/phone_black_back.png)`,
    // backgroundSize: "100% auto",
    // backgroundPosition: "center center",
    // backgroundRepeat: "no-repeat",
    // background: "#707070",
    // background: "#ffffff",
    width: sizeData.draggableWidth + "px",
    height: sizeData.draggableHeight + "px",
    transition: "all .3s",
    ...returnVal
  };
});

// 字体列表
const typefaceOptions = ref([]);
// 当前使用的字体样式
// 计算字体样式
const coverStyle = computed(() => {
  return function (item, index, id) {
    nextTick(() => {
      let domObj = document.getElementById("cover_" + id);
      // 复制一个元素, 计算宽度
      const width = measureTextWithSpan(domObj, domObj.textContent).width;
      state.value[index].width = width;
      state.value[index].height = domObj?.offsetHeight;
    });

    // 计算字体的显示比例
    const size = item.font_size;
    const width = VideoMashup.value.showWidth;
    const height = VideoMashup.value.showHeight;
    // 获取当前缩放的比例
    const { scaleWidth } = resetXY(height, width);
    const font_size = size / scaleWidth
    // const font_size = size / scaleWidth;

    let flower_style;
    // 获取花字的对应样式
    const shadow = () => {
      let { borderw, bordercolor } = item?.preset_styles_config;
      borderw = borderw / 3;
      if (borderw && bordercolor) {
        const shadows = [];
        for (let x = -borderw; x <= borderw; x++) {
          for (let y = -borderw; y <= borderw; y++) {
            if (x !== 0 || y !== 0) {
              shadows.push(`${x}px ${y}px 0 ${bordercolor}`);
            }
          }
        }
        return shadows.join(",");
      } else {
        return "";
      }
    };
    flower_style = {
      // 字体颜色
      color: item?.preset_styles_config.fontcolor || item.color,
      // 转换背景色和透明度
      "background-color": hexToRgba(
        item?.preset_styles_config.boxcolor,
        item?.preset_styles_config.box_color_alpha
      ),
      // 整体透明度
      // 边框的粗细
      padding: `${item?.preset_styles_config?.boxborderw
        ? item?.preset_styles_config?.boxborderw / 4
        : 0
        }px`,
      // "border-radius": item?.preset_styles_config?.boxradius / 3 + "px",
      "text-shadow": shadow(),
    };

    const returnData = {
      // width: item.width + "px",
      // height: item.height + "px",
      // overflow: "hidden",
      cursor: "grab",
      "font-size": font_size + "px",
      color: item.color,
      "background-color": item.bg_color,
      "font-weight": item.bold == 1 ? "bold" : "normal",
      "font-style": item.italic == 1 ? "italic" : "normal",
      opacity: item.opacity,
      "font-family": item.font_family,
      textAlign:
        item.alignment == "left"
          ? "left"
          : item.alignment == "right"
            ? "right"
            : "center",
    };

    if (!!flower_style) {
      return {
        ...returnData,
        ...flower_style,
      };
    } else {
      return returnData;
    }
  };
});

const dragEndHandle = (ev, item) => {
  const dom = document.getElementById("cover_" + item.id);
  const width = dom?.offsetWidth;
  // item.x = item.showX - width / 2;
  item.x = ev.x - width / 2;
  item.showX = ev.x;
  item.y = ev.y;
  // 赋值高亮id
  activeTextarea.value = item.id;
  console.log(ev, item, "拖拽结束");
};

const coverForm = ref({
  cover_duration: 0.05,
  poster_url: "",
});

const customFont = (name, url) => {
  const fontFace = new FontFace(name, `url(${url})`);
  fontFace
    .load()
    .then(() => {
      document.fonts.add(fontFace);
      loading.value = false;
    })
    .catch((error) => {
      console.error(error);
      loading.value = false;
    });
};
const Phoneloading = ref(false);

const getFontClass = () => {
  typefaceOptions.value = [];
  request.get("/work_ai", "/user/shotstack/material/fonts/list").then((res) => {
    res.result.map((item) => {
      item.label = item.name;
      item.value = item.material_url;
      typefaceOptions.value.push(item);
    });
    if (!props.coverObj?.list) {
      let material_url = typefaceOptions.value.find(
        (item) => item.name == "站酷快乐体"
      ).material_url;
      coverList.value = [
        {
          width: 200,
          height: 50,
          position: "center",
          typeface: material_url,
          copywriting: "",
          align_type: "center",
          font_size: 32,
          elLeft: 0, // 元素的左偏移量
          elTop: 0, // 元素的右偏移量
          active: true,
          color: "#FFF000",
          backgroundColor: "",
          verticle_position: "center",
          opacity: 1,
          specialKey: "",
          transitionKey: { in: "", out: "" },
        },
      ];
      coverList.value[0].backgroundColor = "#ffffff";
      nextTick(() => {
        coverList.value[0].backgroundColor = "";
      });
      coverForm.value.poster_url = "";
      coverForm.value.cover_duration = 0.05;
      Phoneloading.value = true;
      customFont("HappyZcool-2016", material_url);
    }
  });
};

const close = () => {
  Modal.confirm({
    title: "温馨提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: "当前未保存，是否退出设置，退出后将不会保存这次编辑",
    cancelText: "取消",
    okText: "确认",
    onOk() {
      closeDrawer();
    },
    onCancel() { },
    class: "test",
  });
};

// 点击确定保存数据 ---------
const querData = ref([]);
const querDataone = ref({});
const submitConfirm = () => {
  querData.value = [];
  TitleArr.value.forEach((item) => {
    item.data.forEach((ele) => {
      ele.text = clearWrap(ele.text);
    });
    querData.value.push(item.data);
  });
  querDataone.value.configs = querData.value;
  querDataone.value.type = 1;
  store.dispatch("SetVideoMashupItem", {
    key: "global_text_config",
    value: querDataone.value,
  });
  closeDrawer();
  isActive.value = 0;
};

//标题组
const TitleArr = ref([
  {
    label: "标题组",
    id: 1,
    isselected: false,
    data: [],
  },
]);

// 添加标题组 最多5组
const AddTitleArr = () => {
  if (TitleArr.value.length < 5) {
    TitleArr.value.push({
      label: "标题组",
      id: TitleArr.value.length + 1,
      isselected: false,
      data: [],
    });
    const text_config_data = baseText_config();
    state.value = [text_config_data];
    isActive.value = TitleArr.value.length - 1;
    activeTextarea.value = state.value[0].id;
  } else {
    message.warning("最多只能添加5个标题组!");
  }
};

// 动态添加样式
const isActive = ref(0);
const changeTab = (index) => {
  isActive.value = index;
  state.value = TitleArr.value[isActive.value].data;
  // // 初始赋值id
  activeTextarea.value = state.value[0].id;
};

// 删除标题组 指定一项
const DelTitleArr = (index) => {
  TitleArr.value.splice(index, 1);

  // 在最后一项时，切换为前一项

  nextTick(() => {
    // 获取更新后的数组长度
    const len = TitleArr.value.length;
    // 如果删除的是高亮的项或者更后面的项
    if (index <= isActive.value) {
      // 如果删除的是最后一项，活动项变为新的最后一项
      if (index === len) {
        isActive.value = len - 1;
      } else if (isActive.value > index) {
        // 如果删除的是高亮项之前的项，活动项索引减一
        isActive.value--;
      }
      // 更新其他依赖的状态值
      state.value = TitleArr.value[isActive.value].data;
      activeTextarea.value = state.value[0].id;
    }
    // 如果删除的项在高亮项之前，不需要改变 isActive.value
  });
};

// 监听事件
watch(
  () => state.value,
  (newValue) => {
    TitleArr.value[isActive.value].data = [];
    TitleArr.value[isActive.value].data = newValue;
  },
  { deep: true }
);

const duration = computed({
  get() {
    const text_duration = state.value[activeIndex.value]?.text_duration;
    return text_duration ? text_duration / 1000 : "";
  },
  set(val) {
    state.value[activeIndex.value].text_duration = val * 1000;
  },
});

// 每一项的开始时间
const text_startTime = computed({
  get() {
    return state.value[activeIndex.value].start_time / 1000;
  },
  set(val) {
    state.value[activeIndex.value].start_time = val * 1000;
  },
});

const aiWritingAssistant = ref(null);
const isQuanJU = ref(false);

// 打开ai写作助手
const openAI = () => {
  const cloneData = JSON.parse(JSON.stringify(querDataone.value));
  cloneData.configs = TitleArr.value.map((ele) => {
    return ele.data;
  });
  cloneData.type = global_text_config.value.type;
  aiWritingAssistant.value.showDrawer({
    data: JSON.parse(JSON.stringify(cloneData)),
    type: "title",
  });
};

const refreshKey = ref(0);

const AddAllsetting = () => {
  Modal.confirm({
    title: "视频设置应用到全部标题组",
    icon: createVNode(ExclamationCircleOutlined),
    content: "是否视频设置应用到全部标题组？",
    okText: "确认",
    cancelText: "取消",
    onOk() {
      const data = applyallGlobalTitle({
        state,
        activeTextarea,
        TitleArr,
      });
    },
    onCancel() { },
    class: "test",
  });
};

// 是否显示背景图
const showImg = ref(true);

// 风险词检测
const openRisk = () => {
  console.log(Risk_testRefs.value, "组件sssssss");
  Risk_testRefs.value?.[isActive.value]?.foldOrOpen();
};
const riskWordDetection = ref(null);
const riskWordDetnHandle = () => {
  let text_arr = TitleArr.value[isActive.value].data.map((ele) => ele.text);
  const isImpty = text_arr?.some((item) => item.trim().length > 0);
  // console.log(isImpty)
  if (isImpty) {
    riskWordDetection.value &&
      riskWordDetection.value.showDrawer(text_arr, "literalTitle");
  } else {
    message.warning("请输入字幕");
  }
};

// 导入数据回调
const updateAiData = (data) => {
  console.log(
    data,
    "导入数据回调导入数据回调导入数据回调导入数据回调导入数据回调"
  );
  TitleArr.value = data.global_text_config.configs.map((ele, index) => {
    return {
      label: "标题组",
      id: index + 1,
      isselected: false,
      data: JSON.parse(JSON.stringify(ele)),
    };
  });

  state.value = JSON.parse(JSON.stringify(data.global_text_config.configs[0]));
  activeTextarea.value = state.value[0].id;
  currentDrawerIndex.value = 0;
  nextTick(() => {
    changeHeight();
    observeActiveSpan();
  });
};

// 取消侦听节点的宽度
const unobserveAllSpans = () => {
  const span = document.getElementById("cover_" + activeTextarea.value);
  resizeObserver.value.unobserve(span);
};

defineExpose({
  openDrawer,
  closeDrawer,
});
</script>

<template>
  <div class="literalTitleDrawer" :key="refreshKey">
    <transition>
      <!-- :destroyOnClose="true" -->
      <a-drawer v-model:visible="visible" :destroyOnClose="true" placement="right" :keyboard="true" width="50%"
        :closable="false" style="z-index: 200 !important" :maskClosable="false" :bodyStyle="{
          minWidth: '420px',
          paddingTop: 0,
        }" getContainer=".literalTitleDrawer">
        <slot name="title">
          <div class="title_box">
            <div class="title_top">
              <h1 class="title">全局配置 - 全局文字标题</h1>
              <div class="close" @click="closeDrawer">
                <CloseOutlined />
              </div>
            </div>
            <div class="no-title"></div>
            <div class="no-titles"></div>
          </div>
        </slot>

        <!-- tab栏切换 最多5组 -->
        <!-- v-for="(item, index) in TitleArr" -->
        <!-- v-if="TitleArr.length > 1" -->
        <div class="tab-content">
          <div class="tab-card" :class="{ activeTab: isActive === index }" v-for="(item, index) in TitleArr"
            :key="item.id" @click="changeTab(index)">
            <div class="tab-card-item">
              {{ item?.label || "标题" }}{{ index + 1 }}
            </div>

            <div v-if="TitleArr.length > 1" class="tab-card-icons" @click.stop="DelTitleArr(index)">
              <CloseOutlined />
            </div>
          </div>
          <!-- v-if="TitleArr.length < 5" -->
          <PlusOutlined v-if="TitleArr.length < 5" class="add_titleArr" @click="AddTitleArr"
            style="margin: 13px 8px 0px 8px; font-size: 10px; color: #000" />
        </div>

        <!-- 内容区域 -->
        <div class="content">
          <!-- 添加标题 -->
          <div class="content_item">
            <div class="content_item_top" style="display: flex; justify-content: space-between">
              <div class="content_item_title">
                <h2>添加标题</h2>
                <span>shift + enter 行内折行</span>
              </div>

              <div class="content_item_AI">
                <a-button size="small" :loading="iconLoading" @click="openAI"
                  style="display: flex; align-items: center">
                  <template #icon>
                    <cu-icon type="icon-AIxiezuozhushou"
                      style="color: #2580fd; font-size: 18px; margin-top: 3px"></cu-icon>
                  </template>
                  AI写作助手
                </a-button>
              </div>
            </div>

            <div class="content_main">
              <div class="textarea_title">
                <span class="textarea_tips">最多增加5行标题</span>
                <a-button @click="riskWordDetnHandle()" size="small"
                  style="font-size: 12px; padding-top: 1px; height: 22px">风险词检测</a-button>
                <!-- <a-button @click="openRisk" size="small"
                  style="font-size: 12px; padding-top: 1px; height: 22px;">风险词检测</a-button> -->
              </div>
              <div @click="focusItem(i.id)" class="content_main_item" v-for="(i, index) in state" :key="i.id">
                <div class="textarea_box" :class="{ active_textarea_box: activeTextarea == i.id }">
                  <span class="textarea_span"> 文本{{ index + 1 }} </span>
                  <textarea v-show="activeTextarea == i.id" maxlength="500" @input="autoResize($event)"
                    @change="textAreaChange(index)" @keydown="textareaKeydown($event, index)" v-model="i.text"
                    placeholder="请填写标题内容，按回车增加标题" name="" cols="20" rows="1" :data-textareaId="i.id">
      </textarea>
                  <div v-show="activeTextarea !== i.id" class="lose_focus">
                    {{ i.text }}
                  </div>
                  <div class="textarea_right_btn" v-show="activeTextarea == i.id">
                    <a-button size="small" class="btn_tolead" style="font-size: 13px; line-height: 24px"
                      :disabled="state[currentDrawerIndex] >= 5" @click.stop="openCopyLibraryModal(index, 'copy')">
                      <template #icon> <copy-outlined /></template>
                      <span>文案库导入</span>
                    </a-button>

                    <a-button size="small" class="btn_copy" style="font-size: 13px; line-height: 24px"
                      :disabled="state[currentDrawerIndex] >= 5" @click.stop="addTextareaItem(index, 'copy')">
                      <template #icon> <copy-outlined /></template>
                      <span>创建副本</span></a-button>

                    <span class="textarea_span">{{ i?.text?.length || 0 }}/500</span>
                  </div>
                </div>
              </div>

              <!-- 风险词检测组件 -->
              <!-- <template v-if="TitleArr.length">
                <template v-for="(i, index) in TitleArr" :key="i.id">
                  <Risk_test v-show="index == isActive" ref="Risk_testRefs"
                    :disableSubmit="!i.data.map(ele => ele.text)?.join('').trim()" :type="'text_config'"
                    :text_arr="i.data.map(ele => ele.text)"
                    :risk_data="TitleArr[isActive]?.risk_data_text_config || null">
                  </Risk_test>
                </template>
              </template> -->
            </div>
          </div>

          <!-- 视频设置 -->
          <div class="content_item" style="margin-top: 20px">
            <div class="video_settings_title">
              <h2>视频设置</h2>
              <a-button class="btn_prev" @click="AddAllsetting" style="
                  font-size: 13px;
                  border-radius: 5px;
                  line-height: 20px;
                  padding: 0 16px;
                ">视频设置应用到全部标题组</a-button>
            </div>
            <FancyFont ref="fancyFont" @updateState="updateState" :state="state[activeIndex]"
              :span_id="`cover_${activeTextarea}`" />
            <div class="control_time">
              <div class="control_time_item">
                <span class="control_time_item_title">开始时间</span>
                <a-input-number @focus="timeInputFocus = true" @blur="timeInputFocus = false"
                  v-model:value="text_startTime" style="width: 185px; padding: 0" allowClear :min="0" :max="4000"
                  :step="0.1" :defaultValue="0" string-mode>
                  <template #addonBefore>
                    <span>第</span>
                  </template>
                  <template #addonAfter>
                    <!-- <span class="clear_btn" >x</span> -->
                    <span>秒</span>
                  </template>
                </a-input-number>
              </div>

              <div class="control_time_item">
                <span class="control_time_item_title">持续时长</span>
                <!-- v-model:value="state[activeIndex].text_duration" -->
                <a-input-number @focus="timeInputFocus = true" @blur="timeInputFocus = false" v-model:value="duration"
                  style="width: 130px; padding: 0" allowClear :min="0.1" :max="999999" :step="0.1" :defaultValue="''"
                  string-mode>
                  <template #addonAfter>
                    <!-- <span class="clear_btn" >x</span> -->
                    <span>秒</span>
                  </template>
                </a-input-number>
                <a-tooltip placement="top" color="#282828" :overlayStyle="{
                  'max-width': 'none',
                  'white-space': 'nowrap',
                }">
                  <template #title>
                    <span style="font-size: 12px">当持续时间大于镜头组时长时，标题展示只会持续到视频结束</span>
                  </template>
                  <InfoCircleOutlined class="info_msg"></InfoCircleOutlined>
                </a-tooltip>
              </div>
            </div>
          </div>
          <div id="phoneConCover" :style="{
            opacity: phoneVisible ? 1 : 0,
            transition: 'opacity 0.5s',
          }" class="phoneConCover_content" v-show="phoneVisible">

            <!-- 手机头部 -->
            <div class="mobile-header">
              <div class="time">{{ dayjs().format("HH:mm") }}</div>
              <div class="wife">
                <cu-icon type="icon-xinhao" style="font-size: 12px"></cu-icon>
                <cu-icon type="icon-wife" style="margin: 0 2px; font-size: 14px"></cu-icon>
                <cu-icon type="icon-electricity-full" style="font-size: 14px"></cu-icon>
              </div>
            </div>
            <!-- 模拟抖音背景 -->
            <div class="bgc_content" :style="{
              'background-image': showImg
                ? `url(${utils.staticPath + 'images/workAi/shotstack/bg_cover.png'
                })`
                : '',
            }"></div>

            <!-- 素材背景图 -->
            <div class="bgc_content" :style="{
              ...parentBgc,
              'z-index': 1,
              height: '640px',
              top: '45px',
              left: 0
            }"></div>
            <!-- 底层背景图 -->
            <div class="left_phone_view" :style="{
              ...bgc
            }">
              <!-- <div class="left_phone_view"> -->
              <!-- <a-spin style="width: 100%; height: 640px" :spinning="loading"> -->
              <DraggableContainer :style="resizableStyle" :referenceLineColor="'white'">
                <Vue3DraggableResizable style="transform: translateX(-50%)" v-show="true" v-for="(item, index) in state"
                  :key="'art_con' + item.id" :initW="item.width" :initH="item.height" v-model:x="item.showX"
                  v-model:y="item.y" v-model:w="item.width" v-model:h="item.height" v-model:active="item.active"
                  :draggable="true" :resizable="false" :parent="false" @drag-end="dragEndHandle($event, item)">
                  <!-- <div :style="coverStyle(item, index, item.id)" @mousedown="activeTextarea = item.id"> -->
                  <!-- :initW="item.width" :initH="item.height" -->
                  <!-- :textContent.prop="item.text" -->
                  <span :style="coverStyle(item, index, item.id)" class="editor_content" :id="'cover_' + item.id"
                    :textContent.prop="item.text" @mousedown="activeTextarea = item.id">
                  </span>
                  <!-- {{ item.text }} -->
                  <!-- </div> -->
                </Vue3DraggableResizable>
              </DraggableContainer>
              <!-- </a-spin> -->
            </div>

            <div class="bottom_View_control">
              <a-button @click="showImg = !showImg">{{ showImg ? "关闭" : "开启" }}抖音视图</a-button>
              <!-- <a-button type="primary">
                <CaretRightOutlined />
                预览效果
              </a-button> -->
            </div>
          </div>
        </div>

        <template #footer>
          <div class="bottom_btn">
            <a-button style="margin-right: 15px" @click="close">取消</a-button>
            <a-button type="primary" @click="submitConfirm">确定</a-button>
          </div>
        </template>

        <AIWritingAssistant ref="aiWritingAssistant" :isQuanJU="true" @updateAiData="updateAiData" />
      </a-drawer>
    </transition>
    <!-- 选择素材 -->
    <ChooseMaterial material_type="text" :isClip="true" :multiple="true" :visible="materiallibraryShow"
      @close="closeChooseMaterial($event, 'material_type')" />
    <RiskWordDetection ref="riskWordDetection" />
    <!-- 文案库 -->
    <CopyLibraryModal ref="copyLibraryModal" @importSuccess="closeChooseMaterial" />
  </div>
</template>

<style lang="less" scoped>
.content {
  padding-top: 20px;
  position: relative;

  // 手机样式
  .phoneConCover_content {
    width: 360px;
    height: 730px;
    background-color: #000;
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    border-radius: 20px;
    top: 50%;
    left: calc(calc(100% - 50%) / 2);
    transform: translate(-50%, -50%);
    z-index: 9999;

    .mobile-header {
      height: 44px;
      width: 100%;
      position: absolute;
      left: 0;
      top: 0;
      border-top-left-radius: 20px;
      border-top-right-radius: 20px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.281);
      background: black;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #fff;
      padding: 10px 10px;
      overflow: hidden;
    }

    // 背景图
    .bgc_content {
      position: absolute;
      top: 50px;
      left: 0;
      width: 100%;
      height: 100%;

      background-repeat: no-repeat;
      background-size: cover;
      background-size: 100%;

      /* 添加这一行 */
      pointer-events: none;
      z-index: 1;
    }

    .left_phone_view {
      overflow: hidden;
      position: relative;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      border-bottom: 1px solid rgba(255, 255, 255, 0.281);

      .editor_content {
        outline: none;
        // line-height: 1;
        margin-bottom: 0;
        border: none;
        resize: none;
        height: auto;
        display: inline-block;
        pointer-events: none;
        // overflow: hidden;
        // 换行显示
        white-space: pre-wrap;
        // 不考虑连贯性, 强制换行
        word-break: break-all;
      }
    }

    // 手机下方的控制按钮
    .bottom_View_control {
      position: absolute;
      bottom: -50px;
      left: 50%;
      transform: translate(-50%, 0);
      display: flex;
    }
  }

  .content_item {
    .control_time {
      display: flex;
      flex-direction: column;

      .control_time_item {
        span {
          margin-right: 16px;
          line-height: 30px;
        }

        &:nth-child(1) {
          margin: 20px 0;
        }

        .info_msg {
          margin-left: 12px;
          padding-top: 2px;
        }
      }

      // 清除input 默认样式
      :deep(.ant-input-number-group-wrapper) {
        border-radius: 5px;
        overflow: hidden;
      }

      :deep(.ant-input-number-group-addon) {
        border: none;
        background-color: transparent;
        padding: 0 5px;
        max-width: 30px;

        span {
          margin-right: 0;
        }
      }

      :deep(.ant-input-number-group) {
        background-color: #f4f5f5;
      }

      :deep(.ant-input-number-input) {
        border: none;
        padding-left: 6px;
      }

      :deep(.ant-input-number) {
        border: none;
        background-color: #f4f5f5;

        &:hover {
          border: none;
        }
      }

      :deep(.ant-input-number-focused) {
        box-shadow: none;
      }

      :deep(.ant-input-number-handler) {
        border-right: 1px solid #d9d9d9;
      }
    }

    .content_main {
      background-color: #f6f8fa;
      padding: 12px;
      border-radius: 10px;

      // .textarea_tips {
      //   color: #737a8780;
      //   font-size: 12px;
      // }
      .textarea_title {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        gap: 10px;
        margin-bottom: 10px;

        .textarea_tips {
          color: #737a8780;
          font-size: 12px;
        }
      }

      .content_main_item {
        margin-bottom: 10px;

        .textarea_box {
          width: 100%;
          border: 3px solid transparent;
          display: flex;
          // align-items: center;
          padding: 5px 8px;

          &:hover {
            & .textarea_right_btn .btn_tolead {
              opacity: 1;
            }
          }

          .textarea_span {
            font-size: 12px;
            align-self: flex-start;
            color: #737a87;
            line-height: 26px;
            margin: 0 5px;
          }

          .textarea_right_btn {
            align-self: flex-end;

            .btn_tolead {
              opacity: 0;
              margin-right: 5px;
            }
          }

          textarea {
            flex: 1;
            overflow: hidden;
            line-height: 26px;
            /* 重要：防止用户手动调整大小 */
            resize: none;
            border: none;
            outline: none;
            font-size: 12px;
            color: #1c1f23;
            background-color: transparent;
            padding: 0;
          }

          .lose_focus {
            flex: 1;
            /* 溢出内容隐藏 */
            line-height: 26px;
            overflow: hidden;
            /* 文本溢出显示省略号 */
            text-overflow: ellipsis;
            /* 文本在一行显示 */
            white-space: nowrap;
            font-size: 12px;
            color: #1c1f23;
          }
        }

        .active_textarea_box {
          border-color: var(--ss-primary-color-deprecated-t-20);
          border-radius: 5px;
        }
      }
    }

    .content_item_title {
      display: flex;
      // justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      h2 {
        font-size: 13px;
        font-weight: 600;
        color: #1e1c23;
        margin-bottom: 0;
        margin-right: 10px;
      }

      span {
        font-size: 12px;
        color: #737a87;
      }
    }

    .video_settings_title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20px;

      h2 {
        font-size: 13px;
        font-weight: 600;
        color: #1e1c23;
        margin-bottom: 0;
        margin-right: 10px;
      }
    }
  }
}

// 底部按钮
.bottom_btn {
  padding: 8px 24px;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
}

// 头部样式
.title_box {
  width: 100%;
  padding-bottom: 10px;
  padding-top: 24px;
  position: sticky;
  top: 0;
  z-index: 999;
  background-color: #fff;

  &::after {
    content: "";
    height: 1px;
    width: calc(100% + 48px);
    background-color: #e8e8e8;
    position: absolute;
    bottom: 0;
    left: -24px;
    z-index: 99;
  }

  .no-title {
    width: 25px;
    height: 39px;
    background-color: #fff;
    position: absolute;
    top: 30px;
    left: -25px;
  }

  .no-titles {
    width: 25px;
    height: 39px;
    background-color: #fff;
    position: absolute;
    top: 30px;
    right: -25px;
  }

  .title_top {
    display: flex;
    justify-content: space-between;
    color: #0c0d0e;

    // margin-bottom: 10px;
    h1 {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 4px;
    }

    .close {
      cursor: pointer;
      text-align: center;
      line-height: 29px;
      padding: 0 6px;

      &:hover {
        background-color: #f3f3f4;
      }
    }
  }

  .title_bottom {
    .btn_prev {
      border-radius: 5px;
      padding: 0 16px;
      font-size: 12px;
      height: 28px;
    }
  }
}

// tab栏样式
.tab-content {
  margin-top: 12px;
  padding-bottom: 5px; // height: 36px;
  display: flex;
  position: sticky;
  top: 0;
  z-index: 996;
  overflow-x: auto;

  &::-webkit-scrollbar {
    width: 8px;
    /* 滚动条的宽度 */
    height: 6px;
    /* 滚动条的高度，垂直滚动条可能用得上 */
  }

  &::-webkit-scrollbar-thumb {
    background: #888;
    /* 滑块的背景颜色 */
    border-radius: 10px;
    /* 滑块的圆角 */
  }

  &::after {
    content: "";
    height: 1px;
    width: 100%;
    background-color: #e8e8e8;
    position: absolute;
    bottom: 0;
    left: 0;
  }

  .tab-card {
    display: flex;
    justify-content: space-between;
    gap: 10px;
    background-color: #f5f7f9;
    padding: 7px 16px;
    color: #5e5e5e;
    margin-right: 10px;
    box-shadow: inset 0 1px 0 #e8e8e8, inset -1px 0 0 #e8e8e8,
      inset 1px 0 0 #e8e8e8;
    cursor: pointer;
    text-wrap: nowrap;

    :hover {
      // color: #fd5859 !important
      color: var(--ss-primary-color-active) !important;
    }

    .tab-card-icons {
      font-size: 10px;
      margin-top: 4px;
    }
  }

  .activeTab {
    color: var(--ss-primary-color-active) !important;
    background-color: #fff !important;
  }
}
</style>
